<template>
  <div class="app">
    <el-form label-width="80px" :rules="rules" :model="password_form" ref="form">
      <el-form-item label="原密码" class="password" prop="oldPassword">
        <el-input v-model="password_form.oldPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" class="password" prop="newPassword1">
        <el-input v-model="password_form.newPassword1" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" class="password" prop="newPassword2">
        <el-input v-model="password_form.newPassword2" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
  name: "password",
  data() {
    return {
      password_form: {
        oldPassword: null,
        newPassword1: null,
        newPassword2: null,
      },

      rules: {
        oldPassword: [
          { required: true, message: "请输入原密码", trigger: "blur" },
          { min: 6, message: "长度至少6个字符", trigger: "change" },
        ],
        newPassword1: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, message: "长度至少6个字符", trigger: "change" },
        ],
        newPassword2: [
          { required: true, message: "请确认新密码", trigger: "blur" },
          { min: 6, message: "长度至少6个字符", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    ...mapState(["userId"]),
  },
  methods: {
    ...mapMutations(["outlogin"]),
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.password_form.newPassword1 != this.password_form.newPassword2) {
            this.$message.error("两次密码不一致");
            return;
          }

          this.$https
            .post("/user/password", {
              userid: this.userId,
              oldPassword: this.password_form.oldPassword,
              newPassword: this.password_form.newPassword1,
            })
            .then((data) => {
              if (data.code == 200) {
                this.$message.success("修改成功");
                this.outlogin(this);
              } else {
                this.$message.error(data.data || data.msg || "修改失败");
              }
            })
            .catch((e) => {
              this.$message.error(e);
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.app {
  padding: 20px;
}
.password {
  width: 400px;
}
</style>
